package com.example.earthquake;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.SimpleCursorAdapter;

import com.example.earthquake.entity.Quake;
import com.example.earthquake.provider.EarthquakeProvider;
import com.example.earthquake.service.EarthquakeService;

public class EarthquakeListFragment extends ListFragment implements LoaderCallbacks<Cursor> {
	
	private final static String TAG = "EarthquakeListFragment";

	private SimpleCursorAdapter adapter;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		adapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, null, new String[] { EarthquakeProvider.KEY_SUMMARY }, new int[] { android.R.id.text1 }, 0);
		setListAdapter(adapter);
		
		getLoaderManager().initLoader(0, null, this);
		
		refreshEarthquakes();
	}
	
	public void refreshEarthquakes() {
		
		getLoaderManager().restartLoader(0, null, EarthquakeListFragment.this);
		getActivity().startService(new Intent(getActivity(), EarthquakeService.class));
	}
	
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		String[] projection = new String[] {
				EarthquakeProvider.KEY_ID,
				EarthquakeProvider.KEY_SUMMARY
		};
		
		MainActivity activity = (MainActivity) getActivity();
		
		String where = EarthquakeProvider.KEY_MAGNITUDE + ">" + activity.minimumMagnitude;
		
		CursorLoader loader = new CursorLoader(activity, EarthquakeProvider.CONTENT_URI, projection, where, null, null);
		return loader;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		adapter.swapCursor(data);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		adapter.swapCursor(null);
	}
	
}
